// pages/customer/openSea.js
const app = getApp();
const network = require("../../utils/network.js");
const util = require("../../utils/util.js");
const customerConfig = require("./config/customerConfig");

Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchboxShow: false, // 弹出层显示与否，用于处理滚动穿透
        searchForm: {
            name: null,
            industry_id: null,
            industry_name: null,
            type: null,
            type_name: null,
            apply_user_id: null,
            apply_user_name: null,
            status: null,
            check_status_name: null,
        },
        industry_arr: [],
        type_arr: [{
            id: 1,
            name: '公司盘'
        },
            {
                id: 2,
                name: '个人盘'
            }
        ],
        apply_user_arr: [],
        check_status_arr: [{
            id: 1,
            name: '待审批'
        },
            {
                id: 2,
                name: '已通过'
            },
            {
                id: 3,
                name: '已驳回'
            }
        ],
        curTabListData: {
            list1: [],
            list2: [],
            list3: [],
            list4: []
        },
        tabs: [],
        curTabId: -1,

        fabs: [{
            iconPath: 'https://oa-meilai.obs.cn-jssz1.ctyun.cn/20221102145321081195.png',
            text: '搜索'
        }, {
            iconPath: 'https://oa-meilai.obs.cn-jssz1.ctyun.cn/20221102145517219958.png',
            text: '刷新'
        }]
    },

    async onLoad() {
        await this.getTabs();
    },
    onShow() {
        this.getIndustryList();
        this.getUserListByCode();
    },

    showSearchBox() {
        this.setData({
            searchboxShow: true
        })
    },

    closeSearchBox() {
        this.setData({
            searchboxShow: false
        })
    },
    getTabs() {
        let tabs = [];
        const hasTabs = util.hasBtnRights([
            'customer-open-sea-company',
            'customer-open-sea-personnel',
            'customer-open-to-check',
            'customer-open-apply-my'
        ]);
        const tabsOrigin = [...customerConfig.defaultTabs(app.api.customerOpenSea, app.api.customerOpenSea, false), {
            id: 3,
            name: '待审核',
            request: {
                url: app.api.customerOpenSeaCheckRecord,
                searchParams: {}
            }
        }, {
            id: 4,
            name: '我的申请',
            request: {
                url: app.api.customerOpenSeaCheckRecord,
                params: {
                    isMyApply: true
                },
                searchParams: {}
            }
        }];
        if (hasTabs[0]) tabs.push(tabsOrigin[0]);
        if (hasTabs[1]) tabs.push(tabsOrigin[1]);
        if (hasTabs[2]) tabs.push(tabsOrigin[2]);
        if (hasTabs[3]) tabs.push(tabsOrigin[3]);
        this.setData({
            tabs: tabs,
            curTabId: (tabs || []).length > 0 ? tabs[0].id : -1
        })
    },

    updateTabListData({
                          detail: {
                              index,
                              list: {
                                  id,
                                  name,
                                  list,
                                  listParams
                              }
                          }
                      }) {
        const key = 'curTabListData.list' + id;
        this.setData({
            [key]: list
        }, function () {
            util.hideLoading()
        })
    },

    changeTab({
                  detail: {
                      id
                  }
              }) {
        this.resetSearch();
        this.resetTabSearch();
        this.setData({
            curTabId: id
        });
    },

    applyFollow({
                    detail: {
                        id
                    }
                }) {
        this.selectComponent('.confirm-dialog').show({
            id
        });
    },
    onConfirmApplyFollow({
                             detail: {
                                 id
                             }
                         }) {
        util.showLoading('提交中');
        network.POST({
            uri: app.api.customerOpenSeaApplyFollow,
            params: {
                id
            },
            success(res) {
                util.hideLoading();
                util.showToast('提交成功');
            }
        })
    },

    passFollowApply({
                        detail: {
                            id
                        }
                    }) {
        this.selectComponent('.confirm-pass-dialog').show({
            id
        });
    },
    onConfirmPassFollowApply({
                                 detail: {
                                     id
                                 }
                             }) {
        const _this = this;
        util.showLoading('提交中');
        network.POST({
            uri: app.api.customerOpenSeaApplyFollowPass,
            params: {
                id
            },
            success(res) {
                util.hideLoading();
                util.showToast('已通过');
                _this.selectComponent('.tabListComponent').refreshCurTabList();
            }
        })
    },

    unpassFollowApply({
                          detail: {
                              id
                          }
                      }) {
        this.selectComponent('.confirm-unpass-dialog').show({
            id
        });
    },
    onConfirmUnpassFollowApply({
                                   detail: {
                                       id
                                   }
                               }) {
        const _this = this;
        util.showLoading('提交中');
        network.POST({
            uri: app.api.customerOpenSeaApplyFollowUnpass,
            params: {
                id
            },
            success(res) {
                util.hideLoading();
                util.showToast('已驳回');
                _this.selectComponent('.tabListComponent').refreshCurTabList();
            }
        })
    },

    inputChange(e) {
        this.setData({
            [e.target.dataset.key]: e.detail
        })
    },

    onConfirmIndustry(e) {
        this.setData({
            'searchForm.industry_id': e.detail.value.id,
            'searchForm.industry_name': e.detail.value.name
        });
    },
    getIndustryList() {
        const that = this
        network.GET({
            uri: app.api.industryList,
            success(res) {
                that.setData({
                    industry_arr: res.data
                })
            }
        })
    },
    onConfirmType(e) {
        this.setData({
            'searchForm.type': e.detail.value.id,
            'searchForm.type_name': e.detail.value.name
        });
    },
    getUserListByCode() {
        const that = this
        network.GET({
            uri: app.api.userListByCode,
            params: {
                code: 'Salesperson'
            },
            success(res) {
                that.setData({
                    apply_user_arr: res.data
                })
            }
        })
    },
    onConfirmApplyUser(e) {
        this.setData({
            'searchForm.apply_user_id': e.detail.value.id,
            'searchForm.apply_user_name': e.detail.value.name
        });
    },
    onConfirmCheckStatus(e) {
        this.setData({
            'searchForm.status': e.detail.value.id,
            'searchForm.check_status_name': e.detail.value.name
        });
    },

    clickFab({
                 detail
             }) {
        if (detail === '刷新') {
            this.resetSearch();
            this.resetTabSearch();
            this.selectComponent('.tabListComponent').refreshCurTabList();
        }
        if (detail === '搜索') {
            this.selectComponent('.search-box').show();
        }
    },

    // /**
    //  * 页面相关事件处理函数--监听用户下拉动作
    //  */
    // onPullDownRefresh() {
    //   this.selectComponent('.tabListComponent').handlePullDownRefresh()
    // },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.selectComponent('.tabListComponent').handleReachBottom()
    },

    getCurTab() {
        const _this = this;
        let tIndex = -1;
        _this.data.tabs.forEach((tab, tabIdx) => {
            if (tab.id == _this.data.curTabId) tIndex = tabIdx;
        })
        return {
            tIndex,
            key: 'tabs[' + tIndex + ']'
        };
    },

    onSearch() {
        const _this = this;
        const {
            tIndex,
            key
        } = _this.getCurTab();
        if (tIndex > -1) {
            const _params = JSON.parse(JSON.stringify(_this.data.searchForm || {}));
            let params = {};
            if (!!_params) {
                const keys = Object.keys(_params) || [];
                keys.forEach(key => {
                    if (_params[key] != null && _params[key] != undefined) params[key] = _params[key];
                });
            }
            _this.setData({
                [key + '.request.searchParams']: params
            }, function () {
                _this.selectComponent('.tabListComponent').refreshCurTabList();
                _this.selectComponent('.search-box').close();
            })
        }
    },
    resetTabSearch(cur = true) {
        const _this = this;
        if (cur) {
            const {
                tIndex,
                key
            } = _this.getCurTab();
            if (tIndex > -1) {
                _this.setData({
                    [key + '.request.searchParams']: {}
                })
            }
        } else {
            let obj = {};
            (_this.data.tabs || []).forEach((tab, index) => {
                obj['tabs[' + index + '].request.searchParams'] = {}
            })
            _this.setData(obj)
        }
    },
    resetSearch() {
        this.setData({
            searchForm: {
                name: null,
                industry_id: null,
                industry_name: null,
                type: null,
                type_name: null,
                apply_user_id: null,
                apply_user_name: null,
                status: null,
                check_status_name: null,
            }
        });
        this.selectComponent('.industry-picker').reset();
        this.selectComponent('.type-picker').reset();
        const applyUserCom = this.selectComponent('.apply-user-picker');
        if (!!applyUserCom) applyUserCom.reset();
        const checkStatusCom = this.selectComponent('.check-status-picker');
        if (!!checkStatusCom) checkStatusCom.reset();
        this.selectComponent('.search-box').close();
    },
    onReset() {
        this.resetSearch();
        this.resetTabSearch();
        this.selectComponent('.tabListComponent').refreshCurTabList();
    },
})
